package com.yf.exam.modules.trainingarchives.evaluation.service.impl;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yf.exam.modules.trainingarchives.evaluation.dto.CreateEvaluationDTO;
import com.yf.exam.modules.trainingarchives.evaluation.entity.Evaluation;
import com.yf.exam.modules.trainingarchives.evaluation.entity.EvaluationExplain;
import com.yf.exam.modules.trainingarchives.evaluation.entity.EvaluationItem;
import com.yf.exam.modules.trainingarchives.evaluation.entity.EvaluationItemTemplate;
import com.yf.exam.modules.trainingarchives.evaluation.enums.EvaluationTypeEnum;
import com.yf.exam.modules.trainingarchives.evaluation.mapper.EvaluationMapper;
import com.yf.exam.modules.trainingarchives.evaluation.service.IEvaluationExplainService;
import com.yf.exam.modules.trainingarchives.evaluation.service.IEvaluationItemService;
import com.yf.exam.modules.trainingarchives.evaluation.service.IEvaluationItemTemplateService;
import com.yf.exam.modules.trainingarchives.evaluation.service.IEvaluationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.exam.modules.trainingarchives.evaluation.vo.EvaluationItemVO;
import com.yf.exam.modules.trainingarchives.evaluation.vo.EvaluationVO;
import com.yf.exam.modules.user.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 满意度调查表 服务实现类
 * </p>
 *
 * @author lql
 * @since 2025-01-06
 */
@Service
public class EvaluationServiceImpl extends ServiceImpl<EvaluationMapper, Evaluation> implements IEvaluationService {


    @Resource
    private IEvaluationExplainService evaluationExplainService;
    @Resource
    private IEvaluationItemTemplateService evaluationItemTemplateService;
    @Resource
    private IEvaluationItemService evaluationItemService;

    @Override
    public String createEvaluation(CreateEvaluationDTO reqDTO) {

        //判断要生成的问卷类型，trainingClassScheduleId不为空为课程问卷，为空则为培训问卷
        Evaluation evaluation = new Evaluation();
        evaluation.setTrainingClassInfoId(reqDTO.getTrainingClassInfoId());
        evaluation.setId(IdWorker.getIdStr());
        evaluation.setOrganizationId(UserUtils.getDepartId());
        List<EvaluationItem> evaluationItems;
        if (StringUtils.isNotBlank(reqDTO.getTrainingClassScheduleId())) {//课程问卷
            evaluation.setType(EvaluationTypeEnum.TEACHER.code);
            //校验调查问卷是否存在
            Evaluation evaluationVerify = this.getOne(Wrappers.<Evaluation>lambdaQuery().eq(Evaluation::getTrainingClassInfoId,reqDTO.getTrainingClassInfoId())
                    .eq(Evaluation::getTrainingClassScheduleId,reqDTO.getTrainingClassScheduleId()));
            if (evaluationVerify != null) {
                return evaluationVerify.getId();
            }
            evaluation.setTrainingClassScheduleId(reqDTO.getTrainingClassScheduleId());
            //获取问卷说明
            EvaluationExplain evaluationExplain = evaluationExplainService.getById("1876296252158136322");
            evaluation.setEvaluationExplain(evaluationExplain.getContent());
            //获取问卷项
            List<EvaluationItemTemplate> itemTemplateList = evaluationItemTemplateService.list(Wrappers.<EvaluationItemTemplate>lambdaQuery().eq(EvaluationItemTemplate::getTemplateId, "1876296252158136500"));
            getEvaluationItemTemplateList(itemTemplateList,"1876296252158136500");
            evaluationItems = itemTemplateList.stream().map(item ->{
                EvaluationItem evaluationItem = new EvaluationItem();
                BeanUtils.copyProperties(item,evaluationItem);
                evaluationItem.setEvaluationId(evaluation.getId());
                return evaluationItem;
            }).collect(Collectors.toList());
        } else {//培训问卷
            evaluation.setType(EvaluationTypeEnum.TRAINING.code);
            //校验调查问卷是否存在
            Evaluation evaluationVerify = this.getOne(Wrappers.<Evaluation>lambdaQuery()
                    .eq(Evaluation::getTrainingClassInfoId,reqDTO.getTrainingClassInfoId())
                    .isNull(Evaluation::getTrainingClassScheduleId));
            if (evaluationVerify != null) {
                return evaluationVerify.getId();
            }
            //获取问卷说明
            EvaluationExplain evaluationExplain = evaluationExplainService.getById("1876292813600608258");
            evaluation.setEvaluationExplain(evaluationExplain.getContent());
            //获取问卷项
            List<EvaluationItemTemplate> itemTemplateList = evaluationItemTemplateService.list(Wrappers.<EvaluationItemTemplate>lambdaQuery().eq(EvaluationItemTemplate::getTemplateId, "1876296252158136400"));
            getEvaluationItemTemplateList(itemTemplateList,"1876296252158136400");
            evaluationItems = itemTemplateList.stream().map(item ->{
                EvaluationItem evaluationItem = new EvaluationItem();
                BeanUtils.copyProperties(item,evaluationItem);
                evaluationItem.setEvaluationId(evaluation.getId());
                return evaluationItem;
            }).collect(Collectors.toList());
        }
        this.save(evaluation);
        if (evaluationItems != null && evaluationItems.size() > 0){
            evaluationItemService.saveBatch(evaluationItems);
        }
        return evaluation.getId();
    }

    @Override
    public EvaluationVO getEvaluation(String id) {
        //获取基础信息
        EvaluationVO evaluationVO = baseMapper.getEvaluation(id);
        //获取问卷项
        List<EvaluationItem> evaluationItemList = evaluationItemService.list(Wrappers.<EvaluationItem>lambdaQuery().eq(EvaluationItem::getEvaluationId,id));
        List<EvaluationItemVO> evaluationItemVOList = evaluationItemList.stream().map(item ->{
            EvaluationItemVO evaluationItemVO = new EvaluationItemVO();
            BeanUtils.copyProperties(item,evaluationItemVO);
            return evaluationItemVO;
        }).collect(Collectors.toList());
        evaluationVO.setEvaluationItemVO(buildTree(evaluationItemVOList));
        return evaluationVO;
    }

    private void getEvaluationItemTemplateList(List<EvaluationItemTemplate> itemTemplateList,String parentId) {
        String newParentId = IdWorker.getIdStr();
        for (EvaluationItemTemplate itemTemplate : itemTemplateList) {
            if (itemTemplate.getId().equals(parentId)){
                itemTemplate.setId(newParentId);
            }
            if (itemTemplate.getParentId().equals(parentId)) {
                itemTemplate.setParentId(newParentId);
                getEvaluationItemTemplateList(itemTemplateList,itemTemplate.getId());
            }
        }
    }

    public static EvaluationItemVO buildTree(List<EvaluationItemVO> nodes) {
        Map<String, EvaluationItemVO> nodeMap = new HashMap<>();
        EvaluationItemVO root = new EvaluationItemVO();

        // Populate the nodeMap with all nodes
        for (EvaluationItemVO node : nodes) {
            nodeMap.put(node.getId(), node);
        }

        // Build the tree structure
        for (EvaluationItemVO node : nodes) {
            if (node.getParentId().equals("0")) {
                root = node;
            } else {
                EvaluationItemVO parent = nodeMap.get(node.getParentId());
                if (parent != null) {
                    parent.getChildren().add(node);
                }
            }
        }
        return root;
    }
}
